package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.admin.SetmealService;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Service("adminSetmealService")
@Slf4j
public class SetmealServiceImpl implements SetmealService {

    private final SetmealMapper setmealMapper;
    private final SetmealDishMapper setmealDishMapper;
    private final DishMapper dishMapper;

    @Autowired
    public SetmealServiceImpl(SetmealMapper setmealMapper, SetmealDishMapper setmealDishMapper, DishMapper dishMapper) {
        this.setmealMapper = setmealMapper;
        this.setmealDishMapper = setmealDishMapper;
        this.dishMapper = dishMapper;
    }

    /**
     * 根据套餐实体DTO 新增套餐
     *
     * @param setmealDTO 套餐DTO
     */
    @Override
    @Transactional
    public void saveSetmealWithDish(SetmealDTO setmealDTO) {
        log.info("执行 新增套餐 业务:{}",setmealDTO);
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        //向套餐表插入数据
        setmealMapper.insertSetmeal(setmeal);

        //获取生成的套餐id
        Long setmealId = setmeal.getId();

        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        //便利套餐菜品关系表集合，并为其中每个套餐菜品关系表的套餐id赋值
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealId));

        //保存套餐和菜品的关联关系
        setmealDishMapper.insertSetmealDishBatch(setmealDishes);
    }

    /**
     * 根据id集合删除套餐
     *
     * @param setmealIds 套餐id集合
     */
    @Override
    @Transactional
    public void deleteSetmealBatch(List<Long> setmealIds) {
        log.info("执行 根据id删除套餐 业务: {}",setmealIds);
        //便利套餐id集合，并用其中的套餐id查询详细信息
        setmealIds.forEach(setmealId -> {
            Setmeal setmeal = setmealMapper.getSetmealById(setmealId);
            //判断是否启售
            if (StatusConstant.ENABLE.equals(setmeal.getStatus())) {
                //启售中的套餐不能删除
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        });

        setmealIds.forEach(setmealId -> {
            //删除套餐表中的数据
            setmealMapper.deleteSetmealById(setmealId);
            //删除套餐菜品关系表中的数据
            setmealDishMapper.deleteSetmealDishBySetmealId(setmealId);
        });
    }

    /**
     * 根据套餐DTO更新套餐
     *
     * @param setmealDTO 套餐DTO
     */
    @Override
    @Transactional
    public void updateSetmeal(SetmealDTO setmealDTO) {
        log.info("执行 根据套餐DTO更新套餐 业务:{}",setmealDTO);
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        //1、修改套餐表，执行update
        setmealMapper.updateSetmeal(setmeal);

        //查询套餐id
        Long setmealId = setmealDTO.getId();

        //2、删除套餐和菜品的关联关系，操作setmeal_dish表，执行delete
        setmealDishMapper.deleteSetmealDishBySetmealId(setmealId);

        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealId));

        //3、重新插入套餐和菜品的关联关系，操作setmeal_dish表，执行insert
        setmealDishMapper.insertSetmealDishBatch(setmealDishes);
    }

    /**
     * 启动或者禁用套餐
     *
     * @param status    套餐状态
     * @param setmealId 套餐id
     */
    @Override
    public void startOrStopSetmeal(Integer status, Long setmealId) {
        log.info("执行 启动或禁用套餐 业务: status:{},setmealId:{}",status,setmealId);
        //起售套餐时，判断套餐内是否有停售菜品，有停售菜品提示"套餐内包含未启售菜品，无法启售"
        if (Objects.equals(status, StatusConstant.ENABLE)) {

            List<Dish> dishList = dishMapper.getDishBySetmealId(setmealId);

            if (dishList != null && !dishList.isEmpty()) {
                //如果套餐内有菜品
                dishList.forEach(dish -> {
                    //检查套餐内是否有未启售菜品
                    if (StatusConstant.DISABLE.equals(dish.getStatus())) {
                        throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                });
            }
        }
        Setmeal setmeal = Setmeal.builder()
                .id(setmealId)
                .status(status)
                .build();
        setmealMapper.updateSetmeal(setmeal);
    }


    /**
     * 分页查询套餐列表
     *
     * @param setmealPageQueryDTO 套餐分页查询DTO
     * @return 套餐分页数据DTO
     */
    @Override
    public PageResult pageQuerySetmeal(SetmealPageQueryDTO setmealPageQueryDTO) {
        log.info("执行 分页查询套餐列表 业务: {}",setmealPageQueryDTO);
        PageHelper.startPage(setmealPageQueryDTO.getPage(),setmealPageQueryDTO.getPageSize());

        try (Page<SetmealVO> page = setmealMapper.pageQuerySetmeal(setmealPageQueryDTO)) {
            return new PageResult(page.getTotal(), page.getResult());
        }
    }



    /**
     * 根据菜品id查询套餐和关联的菜品数据
     *
     * @param dishId 菜品id
     * @return 套餐实体VO
     */
    @Override
    public SetmealVO getSetmealWithDishByDishId(Long dishId) {
        log.info("执行 根据菜品id查询套餐和关联的菜品数据 业务: {}",dishId);
        return setmealMapper.getSetmealWithDishById(dishId);
    }

    /**
     * 根据套餐id查询详细套餐
     *
     * @param setmealId 套餐id
     * @return 套餐实体类VO
     */
    @Override
    public SetmealVO getSetmealWithDishBySetmealId(Long setmealId) {
        log.info("执行 根据套餐id查询套餐以及菜品信息 业务 : {}",setmealId);
        return setmealMapper.getSetmealWithDishById(setmealId);
    }



}
